package report

import (
	"github.com/gin-gonic/gin"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/base"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/oplog"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/infod"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/reportd"
)

// Init 初始化
func Init(route *gin.RouterGroup, d core.CmsDomain) {
	ctrl := createCtrl(d)
	// route.GET("replays", ctrl.getInfoPageList)
	// route.GET("infos/:infoid", info.getInfo)

	route.POST("", oplog.OplogRoute("api发布评论", "cms/api/report/add", ctrl.postReport))

}
func createCtrl(d core.CmsDomain) *reportCtrl {
	return &reportCtrl{
		BaseContrl: base.BaseContrl{
			Domain: d,
		},
		rear: d.Report().ReportAggregateRoot(),
		iar:  d.Info().InfoAggregateRoot(),
	}
}

type reportCtrl struct {
	base.BaseContrl
	rear reportd.ReportAggregateRoot
	iar  infod.InfoAggregateRoot
}

type reqPostReport struct {
	Content    string   `json:"content" bind:"required,min=10,max=500"`
	TargetType int      `json:"target_type" bind:"required"`
	TargetID   string   `json:"target_id" bind:"required"`
	Tags       []string `json:"tags" bind:"required，min=1"`
}

func (c reportCtrl) postReport(ctx *gin.Context) {
	dctx := c.DDDContext(ctx)
	uid := dctx.UID()
	if uid == "" {
		c.ErrUnauthorized(ctx, "未登录不能举报")
		return
	}
	var req reqPostReport
	if err := ctx.BindJSON(&req); err != nil {
		c.ErrBadRequestByBind(ctx, 1, err)
		return
	}
	switch req.TargetType {
	case reportd.TargetTypeInfo:
		i, err := c.iar.GetInfo(dctx, req.TargetID)
		if err != nil {
			c.ErrServerError(ctx, 2, "查询指定信息失败", err)
			return
		}
		if i == nil {
			c.ErrBadRequest(ctx, 3, "找不到指定的信息")
			return
		}
		if i.Status != infod.IStatusPublished {
			c.ErrBadRequest(ctx, 4, "指定信息状态错误不能举报")
			return
		}
	default:
		// 不做校验
	}
	if _, err := c.rear.AddReport(dctx, reportd.ReportDesc{
		Content:    req.Content,
		TargetID:   req.TargetID,
		TargetType: req.TargetType,
		UID:        uid,
		Tags:       req.Tags,
	}); err != nil {
		c.ErrServerError(ctx, 2, "保存失败", err)
		return
	}
	c.Success(ctx, nil)
	return

}
